package lib.optional;

import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;

public class OptionalTest {
    @Test
    public void test01() {
        Optional<String> fullName = Optional.ofNullable(null);
        System.out.println("full name is set?" + fullName.isPresent());
        System.out.println("full name:" + fullName.orElseGet(() -> "[none]"));
        System.out.println(fullName.map(s -> "key" + s + "!").orElse("hey stranger!"));


        Optional<String> firstName = Optional.ofNullable("Tom");
        System.out.println("firstName name is set?" + firstName.isPresent());
        System.out.println("firstName name:" + firstName.orElseGet(() -> "[none]"));
        System.out.println(firstName.map(s -> "hey" + s + "!").orElse("hey stranger!"));
    }

    @Test
    public void testNotGetNulFromMap() {
        Map<String, Object> map = new HashMap<>();
        //normal
        Object value = map.get("key");
        //change Optional进行包装
        Optional<Object> values = Optional.ofNullable(map.get("key"));
    }

    @Test
    public static Optional<Integer> testStringToInteger(String a) {
        try {
            return Optional.of(Integer.parseInt(a));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    @Test
    public int readDuration(Properties props, String name) {
        String value = props.getProperty(name);
        if (null != value) {
            try {
                int i = Integer.parseInt(value);
                if (i > 0) {
                    return i;
                }
            } catch (NumberFormatException e) {
                return 0;
            }
        } else {
            return 0;
        }
        return 0;
    }

    @Test
    public int readDuration2(Properties props, String name) {
        return Optional.ofNullable(props.getProperty(name))
                .flatMap(OptionalTest::testStringToInteger)
                .filter(i -> i > 0).orElse(0);
    }
}
